/**
* 项目名：			应对气候变化项目
* 作  者：			杨海军
* 单  位：			北京超图软件股份有限公司
* 最后修改时间：		以文件日期为准
* 功能说明：           	读取cmiss中农气资料的站点数据
 */
package com.ylpms.too;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RestUtil {

	/**
	 *REST服务地址，依具体环境设置
	 */
	private final String host = "10.172.89.55";
	//private final String host = "7.127.203.212:1529";//通过VPN临时连接的地址
		
	/**
	 * 请求最长时间
	 */
	private final int timeoutInMilliSeconds = 1000 * 60 * 5; // 2 MINUTE
	
	/**
	 * 账户:liying/100081  API:NCC_PGS_SUPERMAP/123456
	 */
	private final String userID = "BEXA_YGZX_sxnqzx";
	
	/**
	 * 密码
	 */
	private final String passWord = "81619505";

	/**
	 * REST请求服务，获取数据
	 */
	public String getRestData(String params) {
		StringBuilder retStr = new StringBuilder();
		URI uri = null;
		URL url = null;
		BufferedReader reader = null;
		URLConnection con;
		try {
			
			//ServiceManager.getLogger().debug("发出CIMISS请求:http://" + this.host + "/cimiss-web/api?" + params);
					
			uri = new URI("http", this.host, "/cimiss-web/api", params, "");
			url = uri.toURL();
			con = url.openConnection();

			con.setConnectTimeout(this.timeoutInMilliSeconds);
			reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
			String line = reader.readLine();
			while (line != null) {
				retStr.append(line).append("\r\n");
				line = reader.readLine();
			}
			reader.close();
			//ServiceManager.getLogger().debug("返回CIMISS请求:结果");
		} catch (Exception ex1) {
			//ServiceManager.getLogger().debug("CIMISS请求发生异常");
			ex1.printStackTrace();
		} finally {
			if (null != reader) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return retStr.toString();
	}
	
//	/**
//	 * 根据传入的参数获取JSON数组
//	 * @param params
//	 * @return
//	 */
//	public JSONArray getRestJsonData(String params) {
//		String strData = this.getRestData(params);
//
//		try {
//			JSONObject json = new JSONObject(strData);
//
//			JSONArray results = json.getJSONArray("DS");
//
//			return results;
//		} catch (JSONException e) {
//			//ServiceManager.getLogger().error(strData);
//			//e.printStackTrace();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取查询的Map 结果数组
//	 * @param params
//	 * @return
//	 */
//	public  List<Map<String, Object>> getResutMapData(String params){
//		JSONArray jsonArray = this.getRestJsonData(params);
//		if (jsonArray == null) {
//			return null;
//		}
//		if (jsonArray.length() < 1) {
//			return null;
//		}
//
//		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
//		for (int i = 0; i < jsonArray.length(); i++) {
//
//			JSONObject result = jsonArray.getJSONObject(i);
//			Map<String, Object> data = new HashMap<String, Object>();
//			for (String key : result.keySet()) {
//				data.put(key, result.get(key));
//			}
//			dataList.add(data);
//		}
//
//		return dataList;
//	}

	/**
	 * 根据输入的信息获取对应的查询参数
	 * @param interfaceId
	 * @param dataCode
	 * @param elements
	 * @param times
	 * @param limits
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	public String getParams(String interfaceId, String dataCode, String []elements, String []times, int limits, Map<String, String> paramMap) throws Exception{
		
		if(interfaceId == null  || interfaceId.equals("")){
			throw new Exception("interfaceId can not be empty");
		}
		
		if (dataCode == null || dataCode.equals("")){
			throw new Exception("dataCode can not be empty");
		}
		
		/*if (elements == null || elements.length <1){
			throw new Exception("elements can not be empty");
		}*/
		
		StringBuilder sb = new StringBuilder();
		sb.append("userId=" + this.userID);
		sb.append("&pwd=" + this.passWord);
		sb.append("&interfaceId=" + interfaceId);
		sb.append("&dataCode=" + dataCode);
		if (elements != null){
			sb.append("&elements=");
			for(int i=0; i<elements.length; i++){
				sb.append(elements[i].trim());
				if (i != elements.length - 1){
					sb.append(",");
				}
			}
		}
		
		if (paramMap != null){
			for(String key : paramMap.keySet()){
				sb.append("&" + key + "=" + paramMap.get(key).toString());
			}
		}
		
		
		if(times != null){
			if((times.length == 2 && interfaceId.contains("TimeRange") ) || interfaceId.equals("statSurfEleByStaIDRange") || interfaceId.equals("statSurfEleInRegion")){
				sb.append("&timeRange=[" + times[0] + "," + times[1] + "]");
			}
			else if(times.length == 1){
				sb.append("&times=" + times[0]);
			}
			else if (times.length == 2){
				sb.append("&times=" + times[1]);
			}
		}
		
		if (limits >0){
			sb.append("&limitCnt=" + Integer.toString(limits));
		}
		sb.append("&dataFormat=json");
		
		return sb.toString();
	}

	public String getStatParams(String oldParams, String minStatID, String maxStaID, String eleValueRanges, String statEles,String adminCodes){
		String param = oldParams;
		if(!minStatID.equals("") && !maxStaID.equals("")){
			param +="&minStaId=" +minStatID + "&maxStaId=" + maxStaID;
		}
		
		if(!eleValueRanges.equals("")){
			param += "&eleValueRanges=" + eleValueRanges;
		}
		
		if (!statEles.equals("")){
			param += "&statEles=" + statEles;
		}
		
		if(!adminCodes.equals("")){
			param += "&adminCodes=" + adminCodes;
		}
		
		return param;		
	}
}

